package cn.anecansaitin.whimsy.common.network;

import cn.anecansaitin.whimsy.Whimsy;
import cn.anecansaitin.whimsy.common.effect.ow.doomfist.RocketPunch;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.neoforged.neoforge.network.handling.PlayPayloadContext;

import java.util.Optional;

public record RocketPunchHitPack(int enemyId) implements CustomPacketPayload {
    public static final ResourceLocation ID = Whimsy.resource("rocket_punch_hit_pack");
    public static final RocketPunchHitPack.ServerHandler HANDLER = new RocketPunchHitPack.ServerHandler();

    public RocketPunchHitPack(FriendlyByteBuf buffer) {
        this(buffer.readVarInt());
    }

    @Override
    public void write(FriendlyByteBuf buffer) {
        buffer.writeVarInt(enemyId);
    }

    @Override
    public ResourceLocation id() {
        return ID;
    }

    public static class ServerHandler {
        private ServerHandler() {}

        public void handle(RocketPunchHitPack data, PlayPayloadContext context) {
            context.workHandler().submitAsync(() -> {
                Optional<Player> optionalPlayer = context.player();

                if (optionalPlayer.isEmpty()) {
                    return;
                }

                Player player = optionalPlayer.get();
                Entity entity = player.level().getEntity(data.enemyId);
                RocketPunch.hurtEntity(player, (LivingEntity) entity);
            });
        }
    }
}
